import React, { useContext, useState } from "react";

import { Button } from "components/ui/Button";
import { Context } from "../lib/Provider";
import { SUNNYSIDE } from "assets/sunnyside";
import metamaskIcon from "assets/icons/metamask_pixel.png";
import walletIcon from "assets/icons/wallet.png";
import fslIcon from "assets/icons/fsl_black.svg";
import { PIXEL_SCALE } from "features/game/lib/constants";
import world from "assets/icons/world.png";

import { Label } from "components/ui/Label";
import { getPromoCode } from "features/game/actions/loadSession";
import { useAppTranslation } from "lib/i18n/useAppTranslations";
import { CONFIG } from "lib/config";
import { Wallet } from "features/wallet/Wallet";

import { useIsPWA } from "lib/utils/hooks/useIsPWA";
import { isMobile } from "mobile-device-detect";
import { Loading } from "./Loading";
import { Connector, CreateConnectorFn } from "@wagmi/core";
import {
  WalletContext,
  bitGetConnector,
  cryptoComConnector,
  fallbackConnector,
  metaMaskConnector,
  okexConnector,
  phantomConnector,
  sequenceConnector,
  walletConnectConnector,
} from "features/wallet/WalletProvider";
import { useActor } from "@xstate/react";
import { useConnect } from "wagmi";

const CONTENT_HEIGHT = 365;

export const SEQUENCE_ICON =
  "";

const OtherWallets: React.FC<{
  onConnect: (connector: Connector | CreateConnectorFn) => void;
  showSequence?: boolean;
}> = ({ onConnect, showSequence = false }) => {
  const { t } = useAppTranslation();

  return (
    <>
      <>
        {showSequence && (
          <Button
            className="mb-1 py-2 text-sm relative"
            onClick={() => onConnect(sequenceConnector)}
          >
            <div className="px-8">
              <img
                src={SEQUENCE_ICON}
                className="w-7 h-7 mobile:w-6 mobile:h-6  ml-2 mr-6 absolute left-0 top-1"
              />
              {"Sequence"}
            </div>
          </Button>
        )}
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(walletConnectConnector)}
        >
          <div className="px-8">
            <svg
              height="25"
              viewBox="0 0 40 25"
              width="40"
              xmlns="http://www.w3.org/2000/svg"
              className="w-7 h-7   ml-2 mr-6 absolute left-0 top-1"
            >
              <path
                d="m8.19180572 4.83416816c6.52149658-6.38508884 17.09493158-6.38508884 23.61642788 0l.7848727.76845565c.3260748.31925442.3260748.83686816 0 1.15612272l-2.6848927 2.62873374c-.1630375.15962734-.4273733.15962734-.5904108 0l-1.0800779-1.05748639c-4.5495589-4.45439756-11.9258514-4.45439756-16.4754105 0l-1.1566741 1.13248068c-.1630376.15962721-.4273735.15962721-.5904108 0l-2.68489263-2.62873375c-.32607483-.31925456-.32607483-.83686829 0-1.15612272zm29.16903948 5.43649934 2.3895596 2.3395862c.3260732.319253.3260751.8368636.0000041 1.1561187l-10.7746894 10.5494845c-.3260726.3192568-.8547443.3192604-1.1808214.0000083-.0000013-.0000013-.0000029-.0000029-.0000042-.0000043l-7.6472191-7.4872762c-.0815187-.0798136-.2136867-.0798136-.2952053 0-.0000006.0000005-.000001.000001-.0000015.0000014l-7.6470562 7.4872708c-.3260715.3192576-.8547434.319263-1.1808215.0000116-.0000019-.0000018-.0000039-.0000037-.0000059-.0000058l-10.7749893-10.5496247c-.32607469-.3192544-.32607469-.8368682 0-1.1561226l2.38956395-2.3395823c.3260747-.31925446.85474652-.31925446 1.18082136 0l7.64733029 7.4873809c.0815188.0798136.2136866.0798136.2952054 0 .0000012-.0000012.0000023-.0000023.0000035-.0000032l7.6469471-7.4873777c.3260673-.31926181.8547392-.31927378 1.1808214-.0000267.0000046.0000045.0000091.000009.0000135.0000135l7.6473203 7.4873909c.0815186.0798135.2136866.0798135.2952053 0l7.6471967-7.4872433c.3260748-.31925458.8547465-.31925458 1.1808213 0z"
                fill="currentColor"
              ></path>
            </svg>
            {"Wallet Connect"}
          </div>
        </Button>

        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(bitGetConnector)}
        >
          <div className="px-8">
            <img
              src={SUNNYSIDE.icons.bitgetIcon}
              alt="Bitget"
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1 rounded-sm"
            />
            <Label
              type="info"
              className="absolute top-1/2 -translate-y-1/2 right-1"
            >
              {t("featured")}
            </Label>
            {"Bitget Wallet"}
          </div>
        </Button>
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(cryptoComConnector)}
        >
          <div className="px-8">
            <img
              src={SUNNYSIDE.icons.cryptoComIcon}
              alt="Crypto.com"
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1 rounded-sm"
            />
            {"Crypto.com Wallet"}
          </div>
        </Button>
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(okexConnector)}
        >
          <div className="px-8">
            <img
              src={SUNNYSIDE.icons.okxIcon}
              alt="OKX"
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1 rounded-sm"
            />
            {"OKX Wallet"}
          </div>
        </Button>
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(phantomConnector)}
        >
          <div className="px-8">
            <img
              src={SUNNYSIDE.icons.phantomIcon}
              alt="Phantom"
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1"
            />
            {"Phantom Wallet"}
          </div>
        </Button>
      </>
    </>
  );
};

interface Props {
  onConnect: (connector: Connector | CreateConnectorFn) => void;
  showAll?: boolean;
}

interface Page {
  page: "home" | "other";
  setPage: (page: "home" | "other") => void;
}

const MainWallets: React.FC<Props & Page> = ({
  onConnect,
  showAll,
  setPage,
  page,
}) => {
  const { t } = useAppTranslation();

  return (
    <>
      <Button
        className="mb-1 py-2 text-sm relative justify-start"
        onClick={() => onConnect(metaMaskConnector)}
      >
        <div className="px-8 mr-2 flex ">
          <img
            src={metamaskIcon}
            className="h-7 ml-2.5 mr-6 absolute left-0 top-1"
          />
          {"Metamask"}
        </div>
      </Button>
      {showAll && (
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(sequenceConnector)}
        >
          <div className="px-8">
            <img
              src={SEQUENCE_ICON}
              className="w-7 h-7 mobile:w-6 mobile:h-6  ml-2 mr-6 absolute left-0 top-1"
            />
            {"Sequence"}
          </div>
        </Button>
      )}

      {page === "home" && (
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => setPage("other")}
        >
          <div className="px-8">
            <img
              src={walletIcon}
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1"
            />
            {t("welcome.otherWallets")}
          </div>
        </Button>
      )}
    </>
  );
};

const PWAWallets: React.FC<Props> = ({ onConnect }) => {
  return (
    <>
      <Button
        className="mb-1 py-2 text-sm relative"
        onClick={() => {
          onConnect(sequenceConnector);
        }}
      >
        <div className="px-8">
          <img
            src={SEQUENCE_ICON}
            className="w-7 h-7 mobile:w-6 mobile:h-6  ml-2 mr-6 absolute left-0 top-1"
          />
          {`Sequence`}
        </div>
      </Button>
      <Button
        className="mb-1 py-2 text-sm relative"
        onClick={() => onConnect(walletConnectConnector)}
      >
        <div className="px-8">
          <svg
            height="25"
            viewBox="0 0 40 25"
            width="40"
            xmlns="http://www.w3.org/2000/svg"
            className="w-7 h-7   ml-2 mr-6 absolute left-0 top-1"
          >
            <path
              d="m8.19180572 4.83416816c6.52149658-6.38508884 17.09493158-6.38508884 23.61642788 0l.7848727.76845565c.3260748.31925442.3260748.83686816 0 1.15612272l-2.6848927 2.62873374c-.1630375.15962734-.4273733.15962734-.5904108 0l-1.0800779-1.05748639c-4.5495589-4.45439756-11.9258514-4.45439756-16.4754105 0l-1.1566741 1.13248068c-.1630376.15962721-.4273735.15962721-.5904108 0l-2.68489263-2.62873375c-.32607483-.31925456-.32607483-.83686829 0-1.15612272zm29.16903948 5.43649934 2.3895596 2.3395862c.3260732.319253.3260751.8368636.0000041 1.1561187l-10.7746894 10.5494845c-.3260726.3192568-.8547443.3192604-1.1808214.0000083-.0000013-.0000013-.0000029-.0000029-.0000042-.0000043l-7.6472191-7.4872762c-.0815187-.0798136-.2136867-.0798136-.2952053 0-.0000006.0000005-.000001.000001-.0000015.0000014l-7.6470562 7.4872708c-.3260715.3192576-.8547434.319263-1.1808215.0000116-.0000019-.0000018-.0000039-.0000037-.0000059-.0000058l-10.7749893-10.5496247c-.32607469-.3192544-.32607469-.8368682 0-1.1561226l2.38956395-2.3395823c.3260747-.31925446.85474652-.31925446 1.18082136 0l7.64733029 7.4873809c.0815188.0798136.2136866.0798136.2952054 0 .0000012-.0000012.0000023-.0000023.0000035-.0000032l7.6469471-7.4873777c.3260673-.31926181.8547392-.31927378 1.1808214-.0000267.0000046.0000045.0000091.000009.0000135.0000135l7.6473203 7.4873909c.0815186.0798135.2136866.0798135.2952053 0l7.6471967-7.4872433c.3260748-.31925458.8547465-.31925458 1.1808213 0z"
              fill="currentColor"
            ></path>
          </svg>
          {`Wallets`}
        </div>
      </Button>
    </>
  );
};

export const Wallets: React.FC<Props> = ({ onConnect, showAll = true }) => {
  const [page, setPage] = useState<"home" | "other">("home");
  const isPWA = useIsPWA();
  const isMobilePWA = isMobile && isPWA;

  const { connectors } = useConnect();

  if (isMobilePWA) {
    return <PWAWallets onConnect={onConnect} showAll={showAll} />;
  }

  const isCryptoCom = getPromoCode() === "crypto-com";
  const isEarnAlliance = getPromoCode() === "EARN";
  const isBitget = getPromoCode() === "BITGET";

  const eip6963Connectors = connectors.filter(
    (connector) => connector.type === "injected" && !!connector.icon,
  );

  // There is an injected provider, but it's not showing up in EIP-6963
  const showFallback = !!window.ethereum && eip6963Connectors.length === 0;

  return (
    <>
      {showFallback && (
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(fallbackConnector)}
        >
          <div className="px-8">
            <img
              src={world}
              className="w-7 h-7 mobile:w-6 mobile:h-6  ml-2 mr-6 absolute left-0 top-1"
            />
            {"Web3 Wallet"}
          </div>
        </Button>
      )}
      <>
        {eip6963Connectors
          .filter((connector) => connector.name !== "MetaMask")
          .map((connector) => (
            <Button
              className="mb-1 py-2 text-sm relative"
              onClick={() => onConnect(connector)}
              key={connector.name}
            >
              <div className="px-8">
                <img
                  src={connector.icon}
                  className="h-7 ml-2.5 mr-6 absolute left-0 top-1 rounded-sm"
                />
                {connector.name}
              </div>
            </Button>
          ))}
      </>
      {isBitget && (
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(bitGetConnector)}
        >
          <div className="px-8">
            <img
              src={SUNNYSIDE.icons.bitgetIcon}
              alt="Bitget"
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1 rounded-sm"
            />
            {"Bitget Wallet"}
          </div>
        </Button>
      )}

      {isCryptoCom && (
        <Button
          className="mb-1 py-2 text-sm relative"
          onClick={() => onConnect(cryptoComConnector)}
        ></Button>
      )}

      {isEarnAlliance && (
        <Button
          className="mb-1 py-2 text-sm relative justify-start"
          onClick={() => onConnect(metaMaskConnector)}
        >
          <div className="px-8 mr-2 flex ">
            <img
              src={metamaskIcon}
              className="h-7 ml-2.5 mr-6 absolute left-0 top-1"
            />
            {"Metamask"}
          </div>
        </Button>
      )}

      {!isCryptoCom && !isEarnAlliance && !isBitget && (
        <>
          {page === "home" && (
            <MainWallets
              onConnect={onConnect}
              showAll={showAll}
              page={page}
              setPage={setPage}
            />
          )}
          {page === "other" && (
            <>
              <MainWallets
                onConnect={onConnect}
                showAll={showAll}
                page={page}
                setPage={setPage}
              />
              <OtherWallets showSequence={!showAll} onConnect={onConnect} />
            </>
          )}
        </>
      )}
    </>
  );
};

export const SignIn: React.FC<{ type: "signin" | "signup" }> = ({ type }) => {
  const { authService } = useContext(Context);
  const { walletService } = useContext(WalletContext);

  const [walletState] = useActor(walletService);
  const [showLoading, setShowLoading] = useState(false);
  const { t } = useAppTranslation();

  if (showLoading) {
    return (
      <div className="">
        <Loading />
      </div>
    );
  }

  const promoCode = getPromoCode();

  return (
    <div
      className="px-2 overflow-y-auto   scrollable"
      style={{ maxHeight: CONTENT_HEIGHT }}
    >
      {walletState.matches("chooseWallet") && (
        <>
          <div
            className="flex items-center mb-2 cursor-pointer "
            onClick={() => authService.send("BACK")}
          >
            <img
              src={SUNNYSIDE.icons.arrow_left}
              className="mr-2"
              style={{
                width: `${PIXEL_SCALE * 8}px`,
              }}
            />
            <span className="text-sm">{t("back")}</span>
          </div>
          <button
            className="w-full p-1 object-contain justify-center items-center cursor-pointer flex mb-1 text-sm relative h-[52px] "
            type="button"
            style={{
              borderImage: `url(${SUNNYSIDE.ui.greyButton})`,
              borderStyle: "solid",
              borderWidth: `8px 8px 10px 8px`,
              borderImageSlice: "3 3 4 3 fill",
              imageRendering: "pixelated",
              borderImageRepeat: "stretch",
              borderRadius: `${PIXEL_SCALE * 5}px`,
              color: "#674544",
            }}
            onClick={() => {
              setShowLoading(true);
              window.location.href = `${CONFIG.API_URL}/auth/google/authorize`;
            }}
          >
            <img src={SUNNYSIDE.icons.googleIcon} />
          </button>
          {!isMobile && type !== "signup" && (
            <Button
              className="mb-1 py-2 text-sm relative"
              onClick={() => {
                setShowLoading(true);
                window.location.href = `${CONFIG.API_URL}/auth/wechat/authorize`;
              }}
            >
              <img
                src={SUNNYSIDE.icons.wechatIcon}
                className="w-7 h-7 mobile:w-6 mobile:h-6  ml-2 mr-6 absolute left-0 top-1"
              />
              {"Wechat"}
            </Button>
          )}

          <Button
            className="mb-1 py-2 text-sm relative"
            onClick={() => {
              setShowLoading(true);
              window.location.href = `${CONFIG.API_URL}/auth/fsl/authorize`;
            }}
          >
            <Label
              type="info"
              className="absolute top-1/2 -translate-y-1/2 right-1"
            >
              {t("featured")}
            </Label>
            <img
              src={fslIcon}
              className="w-10 h-10 left-[2px] mr-6 absolute top-0"
            />
            {"FSL ID"}
          </Button>
        </>
      )}

      <Wallet
        action="login"
        id={0}
        onReady={(payload) => {
          authService.send("CONNECTED", {
            address: payload.address,
            signature: payload.signature,
          });
        }}
      />

      <div className="flex justify-between my-1 items-center">
        <a href="https://discord.gg/sunflowerland" className="mr-4">
          <img
            src="https://img.shields.io/discord/880987707214544966?label=Sunflower%20Land&logo=Discord&style=social"
            alt="Discord: Sunflower Land"
          />
        </a>
        <a
          href="https://docs.sunflower-land.com/getting-started/how-to-start"
          target="_blank"
          rel="noopener noreferrer"
          className="underline text-base font-secondary"
        >
          {t("welcome.needHelp")}
        </a>
      </div>
    </div>
  );
};

export const SignUp = () => <SignIn type="signup" />;
